package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import jodd.net.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理Throwable的处理器，做一个兜底处理
     * */
    @ExceptionHandler(Throwable.class)
    public ResponseResult handleException(Throwable e){
        log.error("全局异常处理器，异常堆栈:{}", ExceptionUtils.getStackTrace(e));
        return ResponseResult.error(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理leadexception的处理器
     * */
    @ExceptionHandler(LeadException.class)
    public ResponseResult handleLeadException(LeadException e){
        return ResponseResult.error(e.getStatus(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        // 获取所有的异常
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        // 拼接异常字符串
        String msg = allErrors.stream().map(error -> error.getDefaultMessage()).collect(Collectors.joining(";"));
        return ResponseResult.error(400, msg);
    }

}
